<?php
// $Id: WinduserModule.php 634 2013-01-13 07:02:16Z tomqin@gmail.com $

/**
 * Part of the framework.
 *
 * @package     Module
 * @version     1.0
 * @copyright   Copyright (C) 2010-2012 SupeFun.com Inc.
 * @author      TomQin <tomqin@gmail.com>
 * @license     http://www.supefun.com/license/
 */

class WinduserModule{

    protected $pwUser  = array();

    protected $pwConfig  = array();

    public function __construct() {
        $config = Base::getConfig('common');
        $config = include($config['phpwind']['base'].'data/cache/config.php');

        $this->pwConfig = $config['data'];
    }

    public function getCookie($name) {
        $per = $this->pwConfig['site']['cookie.pre'];
        return Base::getCookie($per.'_'.$name);
    }

    public function setCookie($name, $value, $life) {
        $per = $this->pwConfig['site']['cookie.pre'];
        $domain = $this->pwConfig['site']['cookie.domain'];
        return Base::setCookie($per.'_'.$name, $value, $life, '/', $domain);
    }

    public function decrypt($str) {
        $key = $this->pwConfig['site']['hash'];
        return PwAuth::decrypt($str, $key);
    }

    public function encrypt($str) {
        $key = $this->pwConfig['site']['hash'];
        return PwAuth::encrypt($str, $key);
    }

    public function getPwdCode($pwd){
        return md5($pwd . $this->pwConfig['site']['hash']);
    }

    public function getCookieUser() {
        $winduser = $this->getCookie('winduser');
        return $this->decrypt(base64_decode($winduser));
    }

    public function checkLogin($user, $pwd) {
        $dbper = '`db_phpwind`.pw_';
        $sql = Db::buildSql("SELECT a.uid, a.password as cookiepwd, b.salt, b.password FROM %s a, %s b
                             WHERE a.uid = b.uid AND b.username LIKE '%s'", $dbper.'user', $dbper.'windid_user', $user);
        $row = Db::query($sql)->fetch_assoc();
        if($row && $row['uid'] > 0 && md5(md5($pwd).$row['salt']) == $row['password']){
            $str = $row['uid']."\t".$this->getPwdCode($row['cookiepwd']);
            $this->setCookie('winduser', base64_encode($this->encrypt($str)), 3600);
            return true;
        }else{
            return false;
        }
    }

    public function initUser(){
        $dbper = '`db_phpwind`.pw_';
        list($uid, $pwd) = explode("\t", $this->getCookieUser());
        if($uid){
            $sql = Db::buildSql("SELECT * FROM %s WHERE uid = %d", $dbper.'user', $uid);
            $row = Db::query($sql)->fetch_assoc();
            if($this->getPwdCode($row['password']) == $pwd)
                return $row;
        }
        return null;
    }
}
